import { Inject, Injectable, Dependencies } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { Users } from 'src/users/users.entity';
import { UsersService } from 'src/users/users.service';
@Dependencies(UsersService, JwtService)
@Injectable()
export class AuthService {
  usersService: UsersService;
  jwtService: JwtService;
  constructor(usersService: UsersService, jwtService: JwtService) {
    this.usersService = usersService;
    this.jwtService = jwtService;
  }

  /**
   *
   * @param name
   * @param password
   */
  async validateUser(
    name: string,
    password: string,
  ): Promise<{
    code: number;
    user: Users;
  }> {
    const user = await this.usersService.findOneByName(name);
    if (user) {
      // TODO 临时不使用密码策略
      if (user.password === password) {
        return {
          code: 1,
          user: user,
        };
      } else {
        return {
          code: 2,
          user: null,
        };
      }
    } else {
      return {
        code: 3,
        user: null,
      };
    }
  }

  /**
   * jwt 签证
   * @param user
   */
  async certificate(user: any) {
    const payload = {
      id: user.id,
      account: user.account,
    };
    const token = this.jwtService.sign(payload, {
      expiresIn: 3600 * 24 * 30,
    });
    console.log(token);
    return token;
  }
}
